package org.sam.swing.table.renderer;

import java.awt.Component;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.WeakHashMap;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import org.sam.swing.renderer.FixedImageIcon;

/**
 * 图片按钮渲染器
 * 
 * @author sam
 *
 */
public class JSTableImageRenderer extends JLabel implements TableCellRenderer, Serializable {

	private static final long serialVersionUID = -3684299559581737726L;

	/**
	 * 资源文件的基础路径
	 */
	private String baseUrl = "";

	/**
	 * 资源文件的基础路径
	 */
	public String getBaseUrl() {
		return baseUrl;
	}

	/**
	 * 资源文件的基础路径
	 */
	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	/**
	 * 图片按钮渲染器
	 */
	public JSTableImageRenderer(String baseUrl) {
		this.setOpaque(true);
		this.setBaseUrl(baseUrl);
	}
	
	/**
	 * 弱引用
	 */
	private WeakHashMap<String, FixedImageIcon> icons = new WeakHashMap<>();
	
	/**
	 * 获取一个图标的引用
	 */
	public FixedImageIcon getIcon(String fileName){
		if (icons.containsKey(fileName))
			return icons.get(fileName);
		
		FixedImageIcon icon = new FixedImageIcon(fileName);
		icons.put(fileName, icon);
		return icon;
	}

	/**
	 * 重写的对象绘制方法
	 */
	@Override
	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
			int row, int column) {

		if (value != null) {
			try {
				// 如果是文件，直接绘制
				if (value instanceof File) {
					File f = (File) value;
					this.setIcon(getIcon(f.getPath()));
				} else if (value instanceof URL) {
					URL f = (URL) value;
					this.setIcon(getIcon(f.getPath()));
				} else {
					this.setIcon(getIcon(this.getBaseUrl() + value));
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		if (isSelected) {
			this.setBackground(table.getSelectionBackground());
		} else {
			this.setBackground(table.getBackground());
		}

		return this;
	}

}
